package cn.loveq.android.manager;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Toast;
import cn.loveq.android.Constants;
import cn.loveq.android.R;
import cn.loveq.android.model.AssistantInfo;
import cn.loveq.android.model.Comment;
import cn.loveq.android.model.Emotions;
import cn.loveq.android.util.Downloader;
import cn.loveq.android.util.TimeUtils;
import cn.loveq.android.widget.InteractiveGalleryViewItem;
import cn.loveq.android.widget.InteractiveGalleryViewItem.IWeiboBoundCallback;

import com.weibo.sina.AccessToken;
import com.weibo.sina.DialogError;
import com.weibo.sina.Oauth2AccessTokenHeader;
import com.weibo.sina.Utility;
import com.weibo.sina.Weibo;
import com.weibo.sina.WeiboDialogListener;
import com.weibo.sina.WeiboException;
import com.weibo.sina.WeiboParameters;

public class SinaWeiboAuthorize {
	private Context mContext;
	private static final String URL_Context_CALLBACK = "weiboandroidsdk://TimeLineContext";
	private static final String FROM = "xweibo";

	// 设置appkey及appsecret
	private static final String CONSUMER_KEY = Constants.SINA_APP_KEY;
	private static final String CONSUMER_SECRET = Constants.SINA_APP_SECRET;
	private static String token;
	private InteractiveGalleryViewItem interactiveGalleryViewItem;
	public SinaWeiboAuthorize(Context mContext) {
		this.mContext = mContext;
	}
	
	public void setInteractiveGalleryViewItem(InteractiveGalleryViewItem interactiveGalleryViewItem){
		this.interactiveGalleryViewItem = interactiveGalleryViewItem;
		this.interactiveGalleryViewItem.setWeiboBoundCallback(new IWeiboBoundCallback() {
			
			@Override
			public void showBoundDialog() {
				showAuthSina(null);
			}
		});
	}
	/*
	 * public void shareGoods(GoodsItem item) { try { Weibo weibo =
	 * Weibo.getInstance(); weibo.setupConsumerConfig(CONSUMER_KEY,
	 * CONSUMER_SECRET);
	 * weibo.setRedirectUrl(Constants.WeiboInfo.SINA_APP_CALLBACK);
	 * 
	 * // 记录信息 SharedPreferences preferences =
	 * mContext.getSharedPreferences("sina_authorize",
	 * Context.MODE_WORLD_READABLE); String access_token =
	 * preferences.getString("access_token", null); Long expires_in =
	 * preferences.getLong("expires_in", 0L);
	 * 
	 * if (access_token != null || expires_in != null) { setAccessToken(weibo,
	 * access_token, expires_in); } else { // 重新授权 authorizeForSina(); return; }
	 * 
	 * // token是否过期 if (!weibo.isSessionValid()) { // 重新授权 authorizeForSina();
	 * Toast.makeText(mContext, "认证过期", 1000).show(); return; }
	 * 
	 * String goodContent = item.getTitle(); String pic_path =
	 * ImageCache.getImageLocalPath(item.getPic_url()); String url =
	 * transformShortUrl(item.getDetail_url()); String shareContent =
	 * StringUtil.myLoveGoods(goodContent, url);
	 * 
	 * weibo.share2weibo(mContext, weibo.getAccessToken().getToken(),
	 * CONSUMER_SECRET, shareContent, pic_path != null ? pic_path : "");
	 * 
	 * // createFriendship(weibo.getAccessToken().getToken()); token =
	 * weibo.getAccessToken().getToken(); } catch (WeiboException e) { int code
	 * = e.getStatusCode(); // 40111 Oauth Error: token_expired! Oauth Token已经过期
	 * // 40112 token_revoked! Oauth Token不合法 // 40113 token_rejected! Oauth
	 * Token不合法 // 重新授权 if (code == 40111 || code == 40112 || code == 40113) {
	 * authorizeForSina(); }
	 * 
	 * } catch (Exception e) { e.printStackTrace(); Toast.makeText(mContext,
	 * "分享失败", 1000).show(); }
	 * 
	 * }
	 */

	/**
	 * 
	 * createFriendship(关注官方微博)
	 * 
	 * @param @param token
	 * @return void
	 * @Exception 异常对象
	 * @since CodingExample　Ver(编码范例查看) 1.1
	 */
	/*
	 * public void createFriendship() { try { if(token != null){ HttpEngine
	 * engine = new HttpEngine();
	 * 
	 * List<NameValuePair> list = new ArrayList<NameValuePair>(); list.add(new
	 * BasicNameValuePair("source", CONSUMER_KEY)); list.add(new
	 * BasicNameValuePair("access_token", token)); list.add(new
	 * BasicNameValuePair("uid", Constants.WeiboInfo.SINA_WEIBO_UID));
	 *//**
	 * 根据新浪微博的工具包获取HTTPClient
	 */
	/*
	 * HttpClient client = Utility.getNewHttpClient(mContext);
	 * 
	 * String responseResult = new String(engine.doPost(client,
	 * Constants.WeiboInfo.SINA_WEIBO_CREATE_FRIENDSHIP, list).getBytes(),
	 * "utf-8"); if (responseResult != null &&
	 * !responseResult.contains("Error Response:")) { JSONObject jsonObject =
	 * new JSONObject(responseResult); Long id = jsonObject.getLong("id"); if
	 * (id != null) { Toast.makeText(mContext, "关注官方微博成功", 1000).show(); } } //
	 * Log.i("test", "-------------- " + responseResult); }
	 * 
	 * } catch (Exception e) { e.printStackTrace(); // Toast.makeText(mContext,
	 * "转换链接出错", 1000).show(); }
	 * 
	 * }
	 *//**
	 * 
	 * transformShortUrl(长连接转换短链接)
	 * 
	 * @param @return
	 * @return String
	 * @Exception 异常对象
	 * @since CodingExample　Ver(编码范例查看) 1.1
	 */
	/*
	 * public String transformShortUrl(String longUrl) { String url_short = "";
	 * try { HttpEngine engine = new HttpEngine(); engine.getHttpClient();
	 * 
	 * StringBuffer sb = new
	 * StringBuffer(Constants.WeiboInfo.SINA_WEIBO_SHORT_URL);
	 * sb.append("?source="
	 * ).append(CONSUMER_KEY).append("&url_long=").append(longUrl);
	 * 
	 * String responseResult = new
	 * String(engine.doGet(sb.toString()).getBytes(), "utf-8");
	 * 
	 * JSONArray object = new JSONArray(responseResult); url_short =
	 * object.getJSONObject(0).getString("url_short"); return url_short; } catch
	 * (Exception e) { e.printStackTrace(); // Toast.makeText(mContext,
	 * "转换链接出错", 1000).show(); } return longUrl; }
	 */

	public void showAuthSina(String str) {
		Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle(mContext.getText(R.string.binding_weibo_title));
		if (str != null) {
			builder.setMessage(str);
		} else {
			builder.setMessage(mContext.getText(R.string.unbinding_weibo));

		}
		builder.setPositiveButton(R.string.go_on,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						authorizeForSina();
						dialog.dismiss();
					}
				});
		builder.setNegativeButton(R.string.exit,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialoginterface, int i) {
						System.exit(0);
					}
				});

		builder.show();
	}

	public void reLoaderAuthToken() {
		Weibo weibo = Weibo.getInstance();
		weibo.setupConsumerConfig(CONSUMER_KEY, CONSUMER_SECRET);
		weibo.setRedirectUrl(Constants.SINA_APP_CALLBACK);

		// 记录信息
		SharedPreferences preferences = mContext.getSharedPreferences(
				"sina_authorize", Context.MODE_WORLD_READABLE);
		String access_token = preferences.getString("access_token", null);
		Long expires_in = preferences.getLong("expires_in", 0L);

		if (access_token != null || expires_in != null) {
			setAccessToken(weibo, access_token, expires_in);
		} else {
			// 重新授权
			// authorizeForSina();
			showAuthSina(null);
			return;
		}

		// token是否过期
		if (!weibo.isSessionValid()) {
			// 重新授权
			// authorizeForSina();
			showAuthSina("认证过期");
			Toast.makeText(mContext, "认证过期", Toast.LENGTH_SHORT).show();
			return;
		}
		Constants.isBoundWeibo = true;
		token = weibo.getAccessToken().getToken();
	}

	/**
	 * 
	 * getFriendshipInfo(根据UID获取某用户的信息)
	 * 
	 * @param @param userId
	 * @return void
	 * @Exception 异常对象
	 * @since CodingExample　Ver(编码范例查看) 1.1
	 */
	public void getFriendshipInfo(Long userId) {
		try {
			Weibo weibo = Weibo.getInstance();
			WeiboParameters bundle = new WeiboParameters();
			// bundle.add("source", Weibo.getAppKey());
			bundle.add("uid", String.valueOf(userId));
			token = weibo.getAccessToken().getToken();
			bundle.add("access_token", token);
			String url = Weibo.SERVER + "users/show.json";
			String rlt = weibo.request(mContext, url, bundle, "GET",
					weibo.getAccessToken());
			Log.i("vita", "rlt = " + rlt);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * getUserTimeLine(获取用户发布的微博)
	 * 
	 * @param @param userId
	 * @param @param count 单页返回的记录条数，默认为50。
	 * @param @param page 返回结果的页码，默认为1。
	 * @return void
	 * @Exception 异常对象
	 * @since CodingExample　Ver(编码范例查看) 1.1
	 */
	public AssistantInfo getUserTimeLine(Long userId, int count, int page) {
		try {
			Weibo weibo = Weibo.getInstance();
			WeiboParameters bundle = new WeiboParameters();
			// bundle.add("source", Weibo.getAppKey());
			bundle.add("uid", String.valueOf(userId));
			token = weibo.getAccessToken().getToken();
			bundle.add("access_token", token);
			bundle.add("count", String.valueOf(count));
			bundle.add("page", String.valueOf(page));
			bundle.add("trim_user", "1");
			String url = Weibo.SERVER + "statuses/user_timeline.json";
			String rlt = weibo.request(mContext, url, bundle, "GET",
					weibo.getAccessToken());
			Log.i("vita", "rlt = " + rlt);

			AssistantInfo info = new AssistantInfo();
			// 解析字符器内容
			JSONObject jsonObject = (JSONObject) new JSONTokener(rlt)
					.nextValue();
			if (jsonObject.has("error_code")) {
				return null;
			}
			JSONArray status = jsonObject.getJSONArray("statuses");
			JSONObject result = status.getJSONObject(0);
			info.setText(result.getString("text"));// 内容
			info.setCreated_at(TimeUtils.GETConvert(
					result.getString("created_at"), TimeUtils.DATE_PATTERN_3));// 创建时间
			info.setComments_count(result.getInt("comments_count"));
			info.setReposts_count(result.getInt("reposts_count"));
			info.setWeibo_id(String.valueOf(result.getLong("id")));
			return info;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * showBatch(根据评论ID批量返回评论信息)
	 * 
	 * @param
	 * @return void
	 * @Exception 异常对象
	 * @since CodingExample　Ver(编码范例查看) 1.1
	 */
	public List<Comment> showBatch(String cid, int count, int page) {
		try {
			Weibo weibo = Weibo.getInstance();
			WeiboParameters bundle = new WeiboParameters();
			// bundle.add("source", Weibo.getAppKey());
			token = weibo.getAccessToken().getToken();
			bundle.add("access_token", token);
			bundle.add("count", String.valueOf(count));
			bundle.add("page", String.valueOf(page));
			bundle.add("id", cid);
			String url = Weibo.SERVER + "comments/show.json";
			String rlt = weibo.request(mContext, url, bundle, "GET",
					weibo.getAccessToken());
			Log.i("vita", "rlt = " + rlt);

			List<Comment> list = new LinkedList<Comment>();
			Comment comment = null;
			// 解析字符器内容
			JSONObject jsonObject = (JSONObject) new JSONTokener(rlt)
					.nextValue();
			if (jsonObject.has("error_code")) {
				return null;
			}
			JSONArray comments = jsonObject.getJSONArray("comments");
			int total = jsonObject.getInt("total_number");
			for (int i = 0; i < comments.length(); i++) {
				comment = new Comment();
				JSONObject object = ((JSONObject) comments.get(i));
				comment.setCommenter(object.getJSONObject("user").getString(
						"name"));
				comment.setCommentContent(object.getString("text"));
				comment.setCommentTime(TimeUtils.GETConvert(
						object.getString("created_at"),
						TimeUtils.DATE_PATTERN_6));
				comment.setCommentId(String.valueOf(object.getLong("id")));
				JSONObject user = object.getJSONObject("user");
				comment.setWid(String.valueOf(user.getLong("id")));
				list.add(comment);
			}

			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * showBatch((对一条微博进行评论)
	 * 
	 * @param @param cid 需要评论的微博ID。
	 * @param @param comment 评论内容，必须做URLencode，内容不超过140个汉字。
	 * @param @param comment_ori 当评论转发微博时，是否评论给原微博，0：否、1：是，默认为0。
	 * @return void
	 * @throws Exception 
	 * @Exception 异常对象
	 * @since CodingExample　Ver(编码范例查看) 1.1
	 */
	public void createComments(String cid, String comment, int comment_ori) throws Exception {
		try {
			Weibo weibo = Weibo.getInstance();
			WeiboParameters bundle = new WeiboParameters();
			// bundle.add("source", Weibo.getAppKey());
			bundle.add("access_token", token);
			bundle.add("comment", comment);
			bundle.add("id", cid);
			bundle.add("comment_ori", String.valueOf(comment_ori));
			String url = Weibo.SERVER + "comments/create.json";
			String rlt = weibo.request(mContext, url, bundle, "POST",
					weibo.getAccessToken());
			Log.i("vita", "rlt = " + rlt);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 
	 * commentsReply(回复一条评论)
	 * 
	 * @param @param cid 需要回复的评论ID。
	 * @param @param id 需要评论的微博ID。
	 * @param @param comment 回复评论内容，必须做URLencode，内容不超过140个汉字。
	 * @param @param comment_ori 当评论转发微博时，是否评论给原微博，0：否、1：是，默认为0。
	 * @return void
	 * @Exception 异常对象
	 * @since CodingExample　Ver(编码范例查看) 1.1
	 */
	public void commentsReply(String cid, String id, String comment,
			int comment_ori) {
		try {
			Weibo weibo = Weibo.getInstance();
			WeiboParameters bundle = new WeiboParameters();
			// bundle.add("source", Weibo.getAppKey());
			bundle.add("access_token", token);
			bundle.add("comment", comment);
			bundle.add("id", id);
			bundle.add("cid", cid);
			bundle.add("comment_ori", String.valueOf(comment_ori));
			String url = Weibo.SERVER + "comments/reply.json";
			String rlt = weibo.request(mContext, url, bundle, "POST",
					weibo.getAccessToken());
			Log.i("vita", "rlt = " + rlt);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void emotions() {
		try {
			File dir = new File(Downloader.SDCARD_PATH + "/"
					+ Downloader.IMAGES_FILE_NAME);
			if (dir.exists()) {
				return;
			}

			Weibo weibo = Weibo.getInstance();
			WeiboParameters bundle = new WeiboParameters();
			bundle.add("access_token", token);
			bundle.add("type", "face");
			bundle.add("language", "cnname");

			String url = Weibo.SERVER + "emotions.json";
			String rlt = weibo.request(mContext, url, bundle, "GET",
					weibo.getAccessToken());
			Log.i("vita", "rlt = " + rlt);

			List<Emotions> list = new ArrayList<Emotions>();
			Emotions emotions = null;
			// 解析字符器内容
			JSONArray jsonObject = (JSONArray) new JSONTokener(rlt).nextValue();
			for (int i = 0; i < 250; i++) {
				JSONObject obj = (JSONObject) jsonObject.get(i);
				emotions = new Emotions();
				emotions.setPhrase(obj.getString("phrase"));
				emotions.setUrl(obj.getString("url"));
				list.add(emotions);
			}
			new downloadEmotion(list).execute("");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	class downloadEmotion extends AsyncTask<String, Integer, String> {
		private List<Emotions> list = new ArrayList<Emotions>();

		public downloadEmotion(List<Emotions> list) {
			super();
			this.list = list;
		}

		@Override
		protected String doInBackground(String... params) {
			int size = list.size();
			for (int i = 0; i < size; i++) {
				Matcher matcher = Pattern.compile("\\[(.+)\\]").matcher(
						list.get(i).getPhrase());
				if (matcher.find()) {
					String find = matcher.group(1) + ".gif";

					Downloader.downloadBitmap(list.get(i).getUrl(), find);
					Log.i("vita", "正在下载 " + i + "  = " + find);
				}
			}
			return null;
		}

	}

	/**
	 * 
	 * checkAuthToken(检查是否保存token)
	 * 
	 * @param
	 * @return void
	 * @Exception 异常对象
	 * @since CodingExample　Ver(编码范例查看) 1.1
	 */
	public boolean checkAuthToken() {
		// 记录信息
		SharedPreferences preferences = mContext.getSharedPreferences(
				"sina_authorize", Context.MODE_WORLD_READABLE);
		String token = preferences.getString("access_token", null);
		String uid = preferences.getString("uid", null);
		if (token == null || uid == null) {
			return false;
		}
		return true;
	}

	private void setAccessToken(Weibo weibo, String token, Long expires_in) {
		AccessToken accessToken = new AccessToken(token, CONSUMER_SECRET);
		accessToken.setExpiresInFromBefore(expires_in);
		weibo.setAccessToken(accessToken);
		// weibo.authorize(mContext, new AuthDialogListener());
		Utility.setAuthorization(new Oauth2AccessTokenHeader());
		weibo.setmAuthDialogListener(new AuthDialogListener());
	}

	/**
	 * 
	 * authorizeForSina(新浪认证)
	 * 
	 * @param
	 * @return void
	 * @Exception 异常对象
	 * @since CodingExample　Ver(编码范例查看) 1.1
	 */
	public void authorizeForSina() {
		Weibo weibo = Weibo.getInstance();
		weibo.setupConsumerConfig(CONSUMER_KEY, CONSUMER_SECRET);

		// Oauth2.0
		// 隐式授权认证方式
		weibo.setRedirectUrl(Constants.SINA_APP_CALLBACK);// 此处回调页内容应该替换为与appkey对应的应用回调页
		// 对应的应用回调页可在开发者登陆新浪微博开发平台之后，
		// 进入我的应用--应用详情--应用信息--高级信息--授权设置--应用回调页进行设置和查看，
		// 应用回调页不可为空

		weibo.authorize(mContext, new AuthDialogListener());

	}

	class AuthDialogListener implements WeiboDialogListener {

		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			String id = values.getString("uid");
			// 记录信息
			SharedPreferences preferences = mContext.getSharedPreferences(
					"sina_authorize", Context.MODE_WORLD_WRITEABLE);

			Editor editor = preferences.edit();
			editor.putString("access_token", token);
			editor.putLong(
					"expires_in",
					(System.currentTimeMillis() + Long.parseLong(expires_in) * 1000));
			editor.putString("uid", id);
			editor.commit();

			AccessToken accessToken = new AccessToken(token, CONSUMER_SECRET);
			accessToken.setExpiresIn(expires_in);
			Weibo.getInstance().setAccessToken(accessToken);

			if(interactiveGalleryViewItem != null){
				interactiveGalleryViewItem.loadData();
				Constants.isBoundWeibo = true;
			}
			// Toast.makeText(mContext, "授权成功", 1000).show(); 

			// 保存信息
			/*
			 * Intent intent = new Intent();
			 * intent.setClass(AuthorizeContext.this, TestContext.class);
			 * startContext(intent);
			 */
		}

		@Override
		public void onError(DialogError e) {
			Toast.makeText(mContext, "Auth error : " + e.getMessage(),
					Toast.LENGTH_LONG).show();
			Constants.isBoundWeibo = false;
			Log.i("vita", "Auth error : " + e.getMessage());
		}

		@Override
		public void onCancel() {
			Toast.makeText(mContext, "Auth cancel", Toast.LENGTH_LONG).show();
			Constants.isBoundWeibo = false;
		}

		@Override
		public void onWeiboException(WeiboException e) {
			Toast.makeText(mContext, "Auth exception : " + e.getMessage(),
					Toast.LENGTH_LONG).show();
			Constants.isBoundWeibo = false;
			Log.i("vita", "Auth exception : " + e.getMessage());
		}

	}

	public void unBoundSinaWeibo() {
		Weibo weibo = Weibo.getInstance();
		weibo.setmAuthDialogListener(null);
		weibo.setAccessToken(null);
		Utility.setAuthorization(null);

		/*
		 * File file = CacheManager.getCacheFileBaseDir(); if(file.exists()){
		 * file.delete(); }
		 */
		CookieSyncManager.createInstance(mContext);
		CookieManager.getInstance().removeAllCookie();

		SharedPreferences sp = mContext.getSharedPreferences("sina_authorize",
				Context.MODE_WORLD_WRITEABLE);
		Editor editor = sp.edit();
		editor.clear();
		editor.commit();
	}
}
